use crate::srv::user::Claims;
use jsonwebtoken::{decode, DecodingKey, Validation, Algorithm};
use std::env;
use actix_web::HttpRequest;
use crate::db_type::Role;
use actix_web::http::HeaderValue;
use crate::api::BusinessError;

pub fn parse_token(token_str: String) -> Option<Claims> {
    let secret = env::var("TOKEN_SECRET")
        .expect(".env 文件中 TOKEN_SECRET 没有设置");
    let token_message = decode::<Claims>(&token_str, &DecodingKey::from_secret(secret.as_ref()), &Validation::default());

    match token_message {
        Ok(data) => {
            Some(data.claims)
        }
        Err(e) => {
            println!("parse_token error:{:#?}", e);
            None
        }
    }
}

#[inline]
pub fn get_token(req: &HttpRequest) -> Option<String> {
    let req = req.headers().get("Token");
    match req {
        Some(token) => {
            let token = format!("{:?}", token);
            let token = (&token[1..token.len() - 1]).to_string();
            return Some(token);
        }
        None => {
            return None;
        }
    }
}

pub fn check_permission(req: &HttpRequest, role: Role) -> Result<Claims, BusinessError> {
    match get_token(req) {
        Some(token) => {
            match parse_token(token) {
                Some(claims) => {
                    // 如果用户权限小于需要的权限，返回权限不足
                    if claims.clone().role.order() < role.order() {
                        return Err(BusinessError::Forbidden);
                    }
                    return Ok(claims);
                }
                None => {
                    return Err(BusinessError::Unauthorized);
                }
            }
        }
        None => {
            return Err(BusinessError::Unauthorized);
        }
    }
}
